package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.EYSystem.dao.*;
import com.neusoft.EYSystem.po.*;
import com.neusoft.EYSystem.service.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class ClientServiceImpl implements ClientService {

    @Autowired
    private ClientDAO clientDAO;

    @Autowired
    private BedDAO bedDAO;

    @Autowired
    private BedUsageDAO bedUsagedao;

    @Autowired
    private CheckinRecordDAO checkinRecordDAO;

    @Autowired
    private MealConfigDAO mealConfigDAO;

    @Autowired
    private CaretakerClientDAO caretakerClientDAO;

    @Autowired
    private ClientNursingProjectDAO clientNursingProjectDAO;

    @Autowired
    private UserDAO userDAO;

    @Override
    public PageResponseBean<List<Client>> listClients(Client client, Long page, Long size) {
        Page<Client> pageObj = new Page<>(page, size);
        QueryWrapper<Client> wrapper = new QueryWrapper<>();
        wrapper.eq("status", "active");

        if (client.getUserId() == null) {
            // 查询user_id为null的自理老人
            wrapper.isNull("user_id");
        } else if (client.getUserId() != null) {
            // 查询指定健康管家负责的护理老人
            wrapper.eq("user_id", client.getUserId());
        }

        // 其他查询条件同前
        if (client.getName() != null && !client.getName().isEmpty()) {
            wrapper.like("name", client.getName());
        }

        IPage<Client> result = clientDAO.selectPage(pageObj, wrapper);

        List<Client> clientList = pageObj.getRecords();
        long total = pageObj.getTotal();
        PageResponseBean<List<Client>> pResponseBean = new PageResponseBean<>();
        if (clientList.isEmpty()) {
            pResponseBean.setStatus(500);
            pResponseBean.setMsg("当前暂无符合要求的老人");
        } else {
            pResponseBean.setStatus(200);
            pResponseBean.setMsg("查询成功");
            pResponseBean.setData(clientList);
            pResponseBean.setTotal(total);
        }
        return pResponseBean;
    }

    @Transactional
    @Override
    public ResponseBean<Integer> logicDeleteClient(Long clientId) {
        Client client = clientDAO.selectById(clientId);
        if (client == null) throw new RuntimeException("客户不存在");
        client.setStatus("hidden");

        ResponseBean<Integer> responseBean = new ResponseBean<>();
        responseBean.setData(clientDAO.updateById(client));
        responseBean.setStatus(500);

        if (client.getBedId() != null) {
            Bed bed = bedDAO.selectById(client.getBedId());
            if (bed != null) {
                bed.setStatus("free");
                bedDAO.updateById(bed);
            } else {
                responseBean.setStatus(400);
                responseBean.setMsg("删除失败,未找到对应的床位信息");
            }
        }

        QueryWrapper<BedUsage> usageWrapper = new QueryWrapper<>();
        usageWrapper.eq("client_id", clientId).in("status", "active","deactive","outward");
        List<BedUsage> usages = bedUsagedao.selectList(usageWrapper);
        if (usages.isEmpty()) {
            responseBean.setStatus(200);
            responseBean.setMsg(responseBean.getMsg() + "但未找到相关的床位使用记录");
            return responseBean;
        } else {
            for (BedUsage usage : usages) {
                usage.setStatus("hidden");
                bedUsagedao.updateById(usage);
            }
            return new ResponseBean<>(200, "客户删除成功，相关床位使用记录已隐藏");
        }
    }

    @Transactional
    @Override
    public ResponseBean<Integer> addClient(ClientAndMeal clientAndMeal) {
        ResponseBean<Integer> response = new ResponseBean<>();
        Client client = clientAndMeal.getClient();
        MealConfig config = clientAndMeal.getMealConfig();
        response.setStatus(200);


        client.setStatus("active");
        Integer user = client.getUserId();
        if(user == null){
            return new ResponseBean<>(400, "用户信息错误");
        }
        client.setUserId(null);
        int demo = clientDAO.insert(client);

        // 更新床位状态
        if (client.getBedId() != null && demo > 0) {
            Bed bed = bedDAO.selectById(client.getBedId());
            if (bed != null && "free".equals(bed.getStatus())) {
                bed.setStatus("occupied");
                bedDAO.updateById(bed);
            } else {
                response.setStatus(400);
                response.setMsg("床位不存在或者已经被使用");
            }
        } else {
            response.setStatus(400);
            response.setMsg("床位ID不能为空");
        }

        // 新增床位使用记录
        if (client.getBedId() != null && client.getCheckinDate() != null) {
            BedUsage usage = new BedUsage();
            usage.setClientId(client.getClientId());
            usage.setBedId(client.getBedId());
            usage.setStartDate(client.getCheckinDate());
            usage.setStatus("使用中");
            usage.setEndDate(client.getContractEndDate());
            bedUsagedao.insert(usage);
        }

        // 返回客户端id
        if (response.getStatus() != 400) {
            // 新增入住记录
            CheckinRecord record = new CheckinRecord();
            record.setClientId(client.getClientId());
            record.setCheckinDate(client.getCheckinDate());
            record.setCheckoutDate(client.getContractEndDate()); // 刚入住未退住
            record.setBedId(client.getBedId());
            record.setUserId(user); // 操作员（可根据实际需求取自当前登录用户）
            record.setNotes(""); // 可填备注
            record.setIsVisible(true);
            if (checkinRecordDAO.insert(record) > 0) {
                // 配置客户饮食习惯
                if (config != null) {
                    config.setClientId(client.getClientId());
                    if (mealConfigDAO.insert(config) <= 0) {
                        response.setStatus(500);
                        response.setMsg("饮食习惯配置失败，请重试");
                    } else {
                        response.setMsg("客户登记成功，饮食习惯配置成功");
                        response.setData(1);
                    }
                }
            } else {
                response.setStatus(500);
                response.setMsg("客户登记成功，但入住记录更新失败,请重试");
            }
        } else {
            response.setMsg("注意" + response.getMsg() + "请再次检查床位状态");
            response.setData(client.getClientId());
        }
        return response;
    }

    @Override
    public PageResponseBean<List<Client>> pageClientWithoutNursingLevel(Long cur, Long number, Client client) {
        Page<Client> page = new Page<>(cur, number);

        // 查询所有status为1的client_id（已绑定护理级别的）
        QueryWrapper<ClientNursingProject> projectWrapper = new QueryWrapper<>();
        projectWrapper.select("client_id").eq("status", 1).groupBy("client_id");
        List<Object> bindedClientIds = clientNursingProjectDAO.selectObjs(projectWrapper); // 返回List<Object>，里面是client_id

        // 构造主查询条件
        QueryWrapper<Client> wrapper = new QueryWrapper<>();
        wrapper.eq("status", "active"); // 状态为visible
        if (client.getName() != null && !client.getName().isEmpty()) {
            wrapper.like("name", client.getName());
        }

        if (!bindedClientIds.isEmpty()) {
            wrapper.notIn("client_id", bindedClientIds); // 排除已配置护理的客户
        }

        // 执行分页查询
        IPage<Client> iPage = clientDAO.selectPage(page, wrapper);
        List<Client> clientList = iPage.getRecords();
        long total = iPage.getTotal();

        // 封装响应
        PageResponseBean<List<Client>> responseBean = new PageResponseBean<>();
        if (clientList.isEmpty()) {
            responseBean.setStatus(500);
            responseBean.setMsg("当前暂无符合要求的客户");
        } else {
            responseBean.setStatus(200);
            responseBean.setMsg("查询成功");
            responseBean.setData(clientList);
            responseBean.setTotal(total);
        }
        return responseBean;
    }

    @Override
    public PageResponseBean<List<Client>> pageClient(Long cur, Long number, Client client) {
        Page<Client> pageObj = new Page<>(cur, number);
        QueryWrapper<Client> wrapper = new QueryWrapper<>();
        wrapper.eq("status", "active");

        // 其他查询条件同前
        if (client.getName() != null && !client.getName().isEmpty()) {
            wrapper.like("name", client.getName());
        }

        IPage<Client> result = clientDAO.selectPage(pageObj, wrapper);

        List<Client> clientList = pageObj.getRecords();
        long total = pageObj.getTotal();
        PageResponseBean<List<Client>> pResponseBean = new PageResponseBean<>();
        if (clientList.isEmpty()) {
            pResponseBean.setStatus(500);
            pResponseBean.setMsg("当前暂无符合要求的老人");
        } else {
            pResponseBean.setStatus(200);
            pResponseBean.setMsg("查询成功");
            pResponseBean.setData(clientList);
            pResponseBean.setTotal(total);
        }
        return pResponseBean;
    }

    @Override
    public PageResponseBean<List<ClientAndUser>> pageClientAndCaretaker(Long cur, Long number, Client client) {
        // 1. 构建分页与查询条件
        Page<Client> pageObj = new Page<>(cur, number);
        QueryWrapper<Client> wrapper = new QueryWrapper<>();
        wrapper.eq("status", "active"); // 查询启用状态的老人

        if (client.getName() != null && !client.getName().isEmpty()) {
            wrapper.like("name", client.getName());
        }

        // 2. 分页查询 Client
        IPage<Client> result = clientDAO.selectPage(pageObj, wrapper);
        List<Client> clientList = result.getRecords();
        long total = result.getTotal();

        // 3. 去重 & 封装 ClientAndUser
        List<ClientAndUser> resultList = new ArrayList<>();
        Set<Integer> processedClientIds = new HashSet<>();

        for (Client c : clientList) {
            Integer clientId = c.getClientId();
            if (processedClientIds.contains(clientId)) {
                continue; // 避免重复添加
            }

            ClientAndUser cu = new ClientAndUser();
            cu.setClient(c);

            QueryWrapper<CaretakerClient> ccWrapper = new QueryWrapper<>();
            ccWrapper.eq("client_id", clientId);
            ccWrapper.eq("is_servered", 1);
            ccWrapper.last("LIMIT 1");

            List<CaretakerClient> ccList = caretakerClientDAO.selectList(ccWrapper);
            if (!ccList.isEmpty()) {
                Integer caretakerId = ccList.get(0).getCaretakerId();
                User caretaker = userDAO.selectById(caretakerId);
                if (caretaker != null) {
                    cu.setUser(caretaker);
                }
            }

            resultList.add(cu);
            processedClientIds.add(clientId);
        }


        // 4. 封装返回
        PageResponseBean<List<ClientAndUser>> response = new PageResponseBean<>();
        if (resultList.isEmpty()) {
            response.setStatus(500);
            response.setMsg("当前暂无符合要求的老人");
        } else {
            response.setStatus(200);
            response.setMsg("查询成功");
            response.setData(resultList);
            response.setTotal(total); // 保持 client 的分页总数
        }

        return response;
    }


}

